import React, { useEffect, useState } from 'react'
import { Upload, Form, App } from 'antd'
import { useModel } from '@umijs/max'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import './index.less'
import ImgCrop from 'antd-img-crop'

const FormUpload = props => {
  const normFile = e => {
    return e
  }

  return (
    <Form.Item
      {...props}
      getValueFromEvent={normFile}
      rules={[
        {
          required: true,
          message: `请上传图片`
        }
      ]}
    >
      <UploadItem text={props.text} aspect={props.aspect} />
    </Form.Item>
  )
}

const UploadCom = ({ imageUrl, loading }) => {
  return (
    <div>
      {imageUrl ? (
        <>
          <img
            src={imageUrl}
            alt='avatar'
            loading='lazy'
            style={{
              width: '100%'
            }}
          />
          <div className='upload_avatar_mask'>
            <div className='upload_avatar_mask_text'>更换图片</div>
          </div>
        </>
      ) : (
        <div>
          {loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div
            style={{
              marginTop: 8
            }}
          >
            上传图片
          </div>
        </div>
      )}
    </div>
  )
}

const UploadItem = props => {
  const { UPLOAD_URL } = useModel('Global')
  const { value, onChange, aspect } = props
  const { message } = App.useApp()
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState()

  // 实现回显
  useEffect(() => {
    if (value) {
      setImageUrl(value)
    }
  }, [value])

  // 上传图片前的校验
  const beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('只能上传png或jpeg格式的图片')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片不能超过2MB')
    }
    return isJpgOrPng && isLt2M
  }

  // 上传图片的回调
  const onUploadChange = e => {
    if (e.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (e.file.status === 'done') {
      const list = e.fileList.filter(i => i.value_attribute || i.response?.data?.img_url)
      onChange(list[0] ? list[0].value_attribute || list[0].response.data.img_url : '')
      setImageUrl(list[0] ? list[0].value_attribute || list[0].response.data.img_url : '')
      message.success('上传成功')
      setLoading(false)
    } else if (e.file.status === 'error') {
      setLoading(false)
      message.error('上传失败')
    }
  }

  return (
    <>
      {aspect ? (
        <ImgCrop showGrid zoomSlider quality={1} aspect={aspect || 1 / 1}>
          <Upload
            maxCount={1}
            action={UPLOAD_URL}
            accept='image/*'
            beforeUpload={beforeUpload}
            onChange={onUploadChange}
            listType='picture-card'
            showUploadList={false}
          >
            <UploadCom imageUrl={imageUrl} loading={loading} />
          </Upload>
        </ImgCrop>
      ) : (
        <Upload
          maxCount={1}
          action={UPLOAD_URL}
          accept='image/*'
          beforeUpload={beforeUpload}
          onChange={onUploadChange}
          listType='picture-card'
          showUploadList={false}
        >
          <UploadCom imageUrl={imageUrl} loading={loading} />
        </Upload>
      )}
    </>
  )
}

export default FormUpload
